using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.Security.Claims;
using System.Text.Encodings.Web;

namespace JGSY.CMS.LowCode.Platform.Infrastructure.Authorization
{
    /// <summary>
    /// 绕过认证处理器 - 用于开发和测试环境的简化认证
    /// </summary>
    public class BypassAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
    {
        public BypassAuthenticationHandler(IOptionsMonitor<AuthenticationSchemeOptions> options,
            ILoggerFactory logger, UrlEncoder encoder)
            : base(options, logger, encoder)
        {
        }

        protected override Task<AuthenticateResult> HandleAuthenticateAsync()
        {
            // 创建一个匿名身份的声明
            var claims = new[]
            {
                new Claim(ClaimTypes.Name, "Anonymous"),
                new Claim(ClaimTypes.NameIdentifier, "anonymous")
            };

            var identity = new ClaimsIdentity(claims, Scheme.Name);
            var principal = new ClaimsPrincipal(identity);
            var ticket = new AuthenticationTicket(principal, Scheme.Name);

            Logger.LogDebug("绕过认证 - 返回匿名用户身份");
            
            return Task.FromResult(AuthenticateResult.Success(ticket));
        }
    }
}
